package org.tlang.parser;

import org.tlang.exception.ParseException;
import org.tlang.keywords.KeyWords;
import org.tlang.lexer.Lexer;
import org.tlang.lexer.token.Token;
import org.tlang.ast.AST;
import org.tlang.ast.list.segment.Segment;

import java.util.ArrayList;
import java.util.List;

/**
 * 代码片段解析器
 */
public class SegmentParser extends ClassParser {

    public SegmentParser(Lexer lexer) {
        super(lexer);
    }

    @Override
    public AST parse(Lexer lexer) throws ParseException {
        this.lexer = lexer;
        return segment();
    }

    /**
     * segment: { statement | function_define }
     */
    protected AST segment() throws ParseException {
        List<AST> result = new ArrayList<>();
        while (lexer.peek(0) != Token.EOF) {
            if (isIdentifier(KeyWords.FUNC)) {
                result.add(functionDefine());
            } else if (isIdentifier(KeyWords.CLASS)) {
                result.add(classDefine());
            } else {
                result.add(statement());
            }
        }
        return Segment.create(result);
    }
}
